<?php
namespace app\controller;
use app\BaseController;
//发送端
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Queue  extends BaseController
{
    const exchange = 'router';
    const queue = 'msgs';
    /**
     * 发送信息
     */
    public static  function pushMessage($data)
    {
        $host = '127.0.0.1';
        $port = 5672;
        $user = 'guest';
        $pwd = 'guest';
        $vhost = '/';
        $connection = new AMQPStreamConnection($host, $port, $user, $pwd, $vhost);
        $channel = $connection->channel();

        $channel->queue_declare(self::queue, false, true, false, false);
        $channel->exchange_declare(self::exchange, 'direct', false, true, false);

        $channel->queue_bind(self::queue, self::exchange);

        $messageBody = $data;
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message, self::exchange);
        $channel->close();
        $connection->close();
        return "ok";
    }
    /**
     * 调用pushMessage就可以发送消息
     */
    public function index()
    {
        for ($x=0; $x<=100; $x++) {
            echo "数字是：$x <br>";
            $data = json_encode(['msg' => '测试数据', 'id' => '15']);
            self::pushMessage($data);
            sleep(1);
        }
    }

}